<?php
// 前台客服AJAX接口
include("../includes/common.php");
include("../includes/chat_auto_reply.php");
@header('Content-Type: application/json; charset=UTF-8');

$act = isset($_GET['act']) ? $_GET['act'] : null;
$user_ip = real_ip();
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

function getSessionId($DB, $user_ip, $user_agent) {
    $row = $DB->getRow("SELECT * FROM shua_chat_session WHERE user_ip=? AND status=1 ORDER BY id DESC LIMIT 1", [$user_ip]);
    if($row) return $row['id'];
    // 自动创建新会话
    $DB->exec("INSERT INTO shua_chat_session (user_ip, user_agent, status, last_msg_time, create_time) VALUES (?,?,?,?,NOW())", [$user_ip, $user_agent, 1, date('Y-m-d H:i:s')]);
    return $DB->lastInsertId();
}

switch($act){
    case 'get':
        // 获取会话和消息
        $session_id = getSessionId($DB, $user_ip, $user_agent);
        $messages = $DB->getAll("SELECT * FROM shua_chat_message WHERE session_id=? ORDER BY id ASC LIMIT 100", [$session_id]);
        $data = [];
        foreach($messages as $msg){
            $data[] = [
                'id' => $msg['id'],
                'sender' => $msg['sender'],
                'content' => $msg['content'],
                'type' => $msg['type'],
                'create_time' => $msg['create_time']
            ];
        }
        exit(json_encode(['code'=>0,'session_id'=>$session_id,'data'=>$data]));
        break;
    case 'send':
        // 发送消息（支持图片）
        $session_id = getSessionId($DB, $user_ip, $user_agent);
        $content = trim($_POST['content'] ?? '');
        $type = 0;
        if(isset($_FILES['image']) && $_FILES['image']['size']>0){
            $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $filename = 'chat_'.date('YmdHis').'_'.rand(1000,9999).'.'.$ext;
            $filepath = ROOT.'assets/img/chat/'.$filename;
            if(!is_dir(ROOT.'assets/img/chat/')) mkdir(ROOT.'assets/img/chat/',0777,true);
            if(move_uploaded_file($_FILES['image']['tmp_name'], $filepath)){
                $content = '/assets/img/chat/'.$filename;
                $type = 1;
            }else{
                exit(json_encode(['code'=>-1,'msg'=>'图片上传失败']));
            }
        }
        if(empty($content)) exit(json_encode(['code'=>-1,'msg'=>'消息内容不能为空']));
        $result = $DB->exec("INSERT INTO shua_chat_message (session_id,sender,content,type,create_time) VALUES (?,?,?,?,NOW())", [$session_id,'user',$content,$type]);
        if($result === false) exit(json_encode(['code'=>-2,'msg'=>'数据库写入失败:'.print_r($DB->error(),true)]));
        $DB->exec("UPDATE shua_chat_session SET last_msg_time=NOW(), status=1 WHERE id=?", [$session_id]);
        
        // 自动回复处理
        $auto_reply = getAutoReply($content);
        if($auto_reply) {
            $DB->exec("INSERT INTO shua_chat_message (session_id,sender,content,type,create_time) VALUES (?,?,?,?,NOW())", [$session_id,'admin',$auto_reply['reply'],0]);
            $DB->exec("UPDATE shua_chat_session SET last_msg_time=NOW() WHERE id=?", [$session_id]);
            exit(json_encode(['code'=>0,'msg'=>'发送成功','auto_reply'=>$auto_reply]));
        }
        
        exit(json_encode(['code'=>0,'msg'=>'发送成功']));
        break;
    default:
        exit(json_encode(['code'=>-4,'msg'=>'No Act']));
} 